/**
 * 公用方法
 */

import { parse } from 'querystring';
export const getPageQuery = () => parse(window.location.href.split('?')[1]);

// 登录结果 callback 处理，返回数据分类存储于 localStorage,设置菜单权限
export function setUserInfo(info) {
  localStorage.setItem('userInfo', JSON.stringify(info));
  if (info.permissions && info.permissions.permissions) {
    const permissions = info.permissions.permissions;
    const clonenAuthority = [];
    permissions.map((auth) => {
      if (auth.displayName) {
        clonenAuthority.push(auth.displayName);
      }
    });
  }
}

// 获取 localStorage 里面的用户信息
export function getUserInfo() {
  const userinfo = localStorage.getItem('userInfo');
  if (userinfo && userinfo !== 'undefined' && userinfo !== '') {
    return JSON.parse(userinfo);
  }
  return null;
}

// 清除缓存
export const clearLocalStorage = () => {
  localStorage.removeItem('userInfo');
  localStorage.removeItem('x-okapi-token');
  sessionStorage.removeItem('isLogin');
  sessionStorage.removeItem('flag');
};

// 菜单权限控制处理
export const menuDataList = (menuList, formatMessage) => {
  const permissions = getUserInfo()?.permissions.permissions;
  const filterUndefined = (item) => typeof item !== 'undefined';
  return menuList
    .map((item) => {
      if (permissions.includes(item.name)) {
        const localItem = {
          ...item,
          path: window.__POWERED_BY_QIANKUN__ ? 'sub-umi' + item.path : item.path,
          name: formatMessage({ id: `menu.${item.name}` }),
          children: item.children ? menuDataList(item.children, formatMessage) : undefined,
        };
        return localItem || null;
      }
    })
    .filter(filterUndefined);
};

/**
 * @param {string} permissonName
 * @returns {Boolean}
 */
export function ifPermission(permissonName) {
  const permsAll = getUserInfo()?.permissions.permissions || [];
  if (permsAll.includes(permissonName)) {
    return true;
  } else {
    return false;
  }
}
